package cn.lbd.zk;

import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

public class ZookeeperConnection implements Watcher{
    //建立一个大小为1的计数器
    static CountDownLatch countDownLatch = new CountDownLatch(1);
    static ZooKeeper zooKeeper = null;
    static String socketAddress = "39.97.191.1:2181";

    @Override
    public void process(WatchedEvent event) {
        //KeeperState发生变化时， EventType永远为None
        if (event.getType() == Event.EventType.None) {
            if (event.getState() == Event.KeeperState.SyncConnected) {
                System.out.println("连接建立成功");
                //连接成功，通知计数器-1
                countDownLatch.countDown();
            } else if (event.getState() == Event.KeeperState.Disconnected) {
                System.out.println("连接断开");
            } else if (event.getState() == Event.KeeperState.Expired) {
                System.out.println("会话超时");
                try {
                    zooKeeper = new ZooKeeper(socketAddress, 5000, new ZookeeperConnection());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } else if (event.getState() == Event.KeeperState.AuthFailed) {
                System.out.println("认证失败");
            }
        }
    }

    public static void main(String[] args) {
        try {
            //异步创建。需要一个计数器对象，大小为1，先把主线程阻塞住，等zkCli和zkServer的连接建立好将计数器-1，计数器减到放行。达到一个异步通知的效果
            zooKeeper = new ZooKeeper(socketAddress, 5000, new ZookeeperConnection());
            //收到通知，计数器（1 - 1 = 0），放行
            countDownLatch.await();
            System.out.println("Session ID => "+zooKeeper.getSessionId());
            zooKeeper.addAuthInfo("digest","lbd:1234567".getBytes());
            byte[] data = zooKeeper.getData("/create/auth", false, null);
            System.out.println(new String(data));
            TimeUnit.SECONDS.sleep(50);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (zooKeeper != null) {
                    zooKeeper.close();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
